<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>聚类分析</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="downloadChart">
          下载图表
        </el-button>
      </div>
      <div id="main" class="chart-main"></div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getToken } from "@/utils/auth";
/* import { WAREHOUSES_PATH } from "../../../api/constants/constants.js"; */

export default {
  name: 'ClusterAnalysisChart',
  data() {
    return {
      chart: null
    };
  },
  mounted() {
    this.fetchData();
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  },
  methods: {
    fetchData() {
      const token = getToken(); 
     /*  const encodedFilePath = encodeURIComponent(WAREHOUSES_PATH); */
      fetch(`${process.env.VUE_APP_BASE_API}/wareHouses/clusterAnalysis`, {
        headers: {
          Authorization: `Bearer ${token}`,
        }
      }) 
      .then(response => response.text()) 
      .then(text => {
          const startIndex = text.indexOf('{');
          const endIndex = text.lastIndexOf('}');
          if (startIndex!== -1 && endIndex!== -1) {
              const jsonText = text.slice(startIndex, endIndex + 1);
              try {
                  const data = JSON.parse(jsonText);
                  if (data.error) {
                      console.error('Error from backend:', data.error);
                      return;
                  }
                  console.log('Fetched data:', data); 
                  this.initChart(data.series);
              } catch (parseError) {
                  console.error('Error parsing JSON:', parseError);
              }
          } else {
              console.error('No valid JSON data found in response');
          }
      })
      .catch(error => {
          console.error('Error fetching data:', error);
      });
    },
    initChart(seriesData) {
      console.log('Initializing chart with data:', seriesData); 
      const chartDom = document.getElementById('main');
      this.chart = echarts.init(chartDom);
      console.log('ECharts instance:', this.chart);
      let option;

      if (!seriesData || seriesData.length === 0 ||!seriesData[0].data || seriesData[0].data.length === 0) {
        console.error('Invalid seriesData for chart initialization');
        return;
      }

      // 提取故障现象和故障原因的唯一值作为 x 轴和 y 轴的类目
      const xAxisData = [...new Set(seriesData[0].data.map(item => item[0]))];
      const yAxisData = [...new Set(seriesData[0].data.map(item => item[1]))];

      // 获取所有聚类结果的唯一值
      const clusterResults = [...new Set(seriesData[0].data.map(item => item[2]))];
      // 定义颜色映射
      const clusterColors = {
        0: 'red',
        1: 'green',
        2: 'blue',
        default: 'gray'
      };
      
      // 生成 series，每个聚类结果一个
      const seriesArr = clusterResults.map(cluster => {
        // 过滤出该聚类的数据点
        const data = seriesData[0].data
          .filter(item => item[2] === cluster)
          .map(item => {
            const xIndex = xAxisData.indexOf(item[0]);
            const yIndex = yAxisData.indexOf(item[1]);
            return [xIndex, yIndex];
          });
        return {
          name: `聚类结果 ${cluster}`,
          type: 'scatter',
          data,
          symbolSize: 20,
          itemStyle: {
            color: clusterColors[cluster] || clusterColors.default
          }
        };
      });

      option = {
        grid: {
          left: 80,
          right: 40,
          top: 60,
          bottom: 60,
          containLabel: true
        },
        legend: {
          show: false
        },
        xAxis: {
          type: 'category',
          data: xAxisData
        },
        yAxis: {
          type: 'category',
          data: yAxisData
        },
        series: seriesArr
      };
      console.log('ECharts option:', option);
      option && this.chart.setOption(option);
    },
    downloadChart() {
      if (!this.chart) {
        this.$message.warning('暂无图表数据');
        return;
      }
      
      try {
        // 获取当前时间作为文件名
        const now = new Date();
        const dateStr = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}`;
        
        const fileName = `聚类分析_${dateStr}.png`;
        
        // 获取图表图片的base64数据
        const imgData = this.chart.getDataURL({
          type: 'png',
          pixelRatio: 2,
          backgroundColor: '#fff'
        });
        
        // 创建下载链接
        const link = document.createElement('a');
        link.href = imgData;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        this.$message.success('图表下载成功');
      } catch (error) {
        console.error('下载图表失败:', error);
        this.$message.error('下载图表失败，请重试');
      }
    }
  }
};
</script>

<style scoped>
.box-card {
  margin: 20px;
  width: 100%;
  max-width: 90%;
  min-width: 0;
  box-sizing: border-box;
}

.chart-main {
  width: 100%;
  height: 700px;
  margin: 0 auto;
  display: block;
}
</style>